package com.example.contextcube;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.contextcube.adapter.RecentQueryAdapter;
import com.example.contextcube.adapter.WordAdapter;
import com.example.contextcube.db.DictionaryDatabaseHelper;
import com.example.contextcube.model.Word;
import com.example.contextcube.util.FavoriteManager;
import com.example.contextcube.util.ToastManager;

import java.util.ArrayList;
import java.util.List;

public class DictionaryFragment extends Fragment {
    private static final String TAG = "DictionaryFragment";
    
    private SearchView searchView;
    private RecyclerView searchResultsRecycler;
    private RecyclerView recentQueriesRecycler;
    private TextView resultsTitle;
    private TextView recentQueriesTitle;
    private TextView emptyView;
    private TextView emptyRecentQueries;
    private ProgressBar progressBar;
    
    private WordAdapter searchAdapter;
    private RecentQueryAdapter recentQueryAdapter;
    private DictionaryDatabaseHelper dbHelper;
    private FavoriteManager favoriteManager;
    
    // 搜索线程和Handler
    private Handler mainHandler;
    private SearchRunnable searchRunnable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dictionary, container, false);
        
        Log.d(TAG, "onCreateView: 初始化词典界面");
        
        // 初始化视图
        initViews(view);
        
        // 初始化数据库助手
        dbHelper = new DictionaryDatabaseHelper(requireContext());
        
        // 初始化FavoriteManager
        favoriteManager = FavoriteManager.getInstance();
        favoriteManager.setDatabaseHelper(dbHelper);
        
        // 初始化Handler
        mainHandler = new Handler(Looper.getMainLooper());
        searchRunnable = new SearchRunnable();
        
        // 设置搜索监听
        setupSearchView();
        
        // 加载最近查询
        loadRecentQueries();
        
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时重新加载最近查询
        loadRecentQueries();
        
        // 刷新搜索结果中的收藏状态
        if (searchAdapter != null && searchAdapter.getItemCount() > 0) {
            searchAdapter.notifyDataSetChanged();
        }
        
        Log.d(TAG, "onResume: 重新加载最近查询并刷新收藏状态");
    }
    
    private void initViews(View view) {
        Log.d(TAG, "initViews: 初始化视图组件");
        
        searchView = view.findViewById(R.id.search_view);
        searchResultsRecycler = view.findViewById(R.id.search_results_recycler);
        recentQueriesRecycler = view.findViewById(R.id.recent_queries_recycler);
        resultsTitle = view.findViewById(R.id.results_title);
        recentQueriesTitle = view.findViewById(R.id.recent_queries_title);
        emptyView = view.findViewById(R.id.empty_view);
        emptyRecentQueries = view.findViewById(R.id.empty_recent_queries);
        progressBar = view.findViewById(R.id.progress_bar);
        
        // 设置搜索结果RecyclerView
        searchResultsRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        searchAdapter = new WordAdapter(this::onWordItemClick);
        searchAdapter.setDatabaseHelper(dbHelper);
        searchAdapter.setOnFavoriteClickListener(this::onFavoriteClick);
        searchAdapter.setWords(new ArrayList<>());
        searchResultsRecycler.setAdapter(searchAdapter);
        
        // 设置最近查询RecyclerView
        recentQueriesRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        recentQueryAdapter = new RecentQueryAdapter(this::onWordItemClick);
        recentQueryAdapter.setDatabaseHelper(dbHelper);
        recentQueryAdapter.setOnFavoriteClickListener(this::onFavoriteClick);
        recentQueryAdapter.setRecentQueries(new ArrayList<>());
        recentQueriesRecycler.setAdapter(recentQueryAdapter);
    }
    
    private void setupSearchView() {
        Log.d(TAG, "setupSearchView: 设置搜索监听");
        
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d(TAG, "onQueryTextSubmit: 提交搜索: " + query);
                
                if (!TextUtils.isEmpty(query)) {
                    performSearch(query);
                    
                    // 当用户点击搜索按钮时，获取搜索结果的第一个单词添加到最近查询
                    addFirstResultToRecentQueries(query);
                }
                return true;
            }
            
            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() >= 2) {
                    // 至少输入2个字符才开始搜索
                    Log.d(TAG, "onQueryTextChange: 搜索: " + newText);
                    performSearch(newText);
                } else if (newText.isEmpty()) {
                    // 搜索框为空时，清空搜索结果
                    Log.d(TAG, "onQueryTextChange: 清空搜索结果");
                    clearSearchResults();
                }
                return true;
            }
        });
    }
    
    private void addFirstResultToRecentQueries(String query) {
        Log.d(TAG, "addFirstResultToRecentQueries: 开始搜索并添加到最近查询: " + query);
        
        // 在后台线程搜索，避免阻塞UI
        new Thread(() -> {
            try {
                // 执行搜索，只获取第一个结果
                final List<Word> results = dbHelper.searchWordsByPrefix(query);
                Log.d(TAG, "addFirstResultToRecentQueries: 搜索结果数量: " + (results != null ? results.size() : 0));
                
                // 在主线程更新UI
                mainHandler.post(() -> {
                    if (results != null && !results.isEmpty()) {
                        // 如果有搜索结果，将第一个结果添加到最近查询
                        Word firstWord = results.get(0);
                        dbHelper.addToRecentQueries(firstWord);
                        Log.d(TAG, "addFirstResultToRecentQueries: 添加到最近查询: " + firstWord.getWord());
                        
                        // 重新加载最近查询列表
                        loadRecentQueries();
                    } else {
                        Log.d(TAG, "addFirstResultToRecentQueries: 没有找到匹配的单词");
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "addFirstResultToRecentQueries: 搜索出错: " + e.getMessage(), e);
            }
        }).start();
    }
    
    private void performSearch(String query) {
        Log.d(TAG, "performSearch: 执行搜索: " + query);
        
        // 显示加载中
        progressBar.setVisibility(View.VISIBLE);
        
        // 取消之前的搜索任务
        mainHandler.removeCallbacks(searchRunnable);
        
        // 设置搜索关键词
        searchRunnable.setQuery(query);
        
        // 延迟300毫秒执行搜索，避免频繁搜索
        mainHandler.postDelayed(searchRunnable, 300);
    }
    
    private void clearSearchResults() {
        resultsTitle.setVisibility(View.GONE);
        searchAdapter.setWords(new ArrayList<>());
        emptyView.setVisibility(View.GONE);
    }
    
    private void loadRecentQueries() {
        Log.d(TAG, "loadRecentQueries: 开始加载最近查询");
        
        // 使用后台线程加载最近查询，避免主线程阻塞
        new Thread(() -> {
            try {
                final List<Word> recentQueries = dbHelper.getRecentQueries();
                Log.d(TAG, "loadRecentQueries: 加载到最近查询数量: " + recentQueries.size());
                
                if (recentQueries.size() > 0) {
                    Log.d(TAG, "loadRecentQueries: 第一个查询: " + recentQueries.get(0).getWord());
                }
                
                // 在主线程更新UI
                mainHandler.post(() -> {
                    try {
                        recentQueryAdapter.setRecentQueries(recentQueries);
                        
                        // 显示或隐藏空视图
                        if (recentQueries.isEmpty()) {
                            Log.d(TAG, "loadRecentQueries: 没有最近查询记录，显示空视图");
                            emptyRecentQueries.setVisibility(View.VISIBLE);
                            recentQueriesRecycler.setVisibility(View.GONE);
                        } else {
                            Log.d(TAG, "loadRecentQueries: 有最近查询记录，显示列表");
                            emptyRecentQueries.setVisibility(View.GONE);
                            recentQueriesRecycler.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "loadRecentQueries: UI更新错误: " + e.getMessage(), e);
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "loadRecentQueries: 加载最近查询出错: " + e.getMessage(), e);
            }
        }).start();
    }
    
    private void onWordItemClick(Word word) {
        Log.d(TAG, "onWordItemClick: 点击单词: " + word.getWord());
        
        // 添加到最近查询
        dbHelper.addToRecentQueries(word);
        
        // 跳转到单词详情页
        Intent intent = new Intent(getActivity(), WordDetailActivity.class);
        intent.putExtra("word", word.getWord());
        intent.putExtra("phonetic", word.getPhonetic());
        intent.putExtra("definition", word.getDefinition());
        intent.putExtra("translation", word.getTranslation());
        startActivity(intent);
    }
    
    /**
     * 处理收藏按钮点击事件
     */
    private void onFavoriteClick(Word word, boolean isFavorite) {
        Log.d(TAG, "onFavoriteClick: " + word.getWord() + ", isFavorite: " + isFavorite);
        
        // 通过FavoriteManager更新数据库和通知其他适配器
        boolean success = favoriteManager.toggleFavorite(word.getWord(), isFavorite);
        
        // 提示用户
        if (success) {
            String message = isFavorite ? 
                    getString(R.string.added_to_favorites, word.getWord()) : 
                    getString(R.string.removed_from_favorites, word.getWord());
            ToastManager.showShort(getContext(), message);
        } else {
            // 操作失败，显示具体的失败原因
            String message = isFavorite ? 
                    getString(R.string.favorite_add_failed, word.getWord()) : 
                    getString(R.string.favorite_remove_failed, word.getWord());
            ToastManager.showShort(getContext(), message);
        }
    }
    
    /**
     * 搜索线程
     */
    private class SearchRunnable implements Runnable {
        private String query;
        
        public void setQuery(String query) {
            this.query = query;
        }
        
        @Override
        public void run() {
            try {
                Log.d(TAG, "SearchRunnable: 开始搜索: " + query);
                
                // 执行搜索
                final List<Word> results = dbHelper.searchWordsByPrefix(query);
                
                Log.d(TAG, "SearchRunnable: 搜索结果数量: " + (results != null ? results.size() : 0));
                
                // 在主线程更新UI
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    
                    if (results != null && !results.isEmpty()) {
                        // 有搜索结果
                        Log.d(TAG, "SearchRunnable: 显示搜索结果");
                        resultsTitle.setVisibility(View.VISIBLE);
                        searchAdapter.setWords(results);
                        emptyView.setVisibility(View.GONE);
                    } else {
                        // 没有搜索结果
                        Log.d(TAG, "SearchRunnable: 没有搜索结果");
                        resultsTitle.setVisibility(View.GONE);
                        searchAdapter.setWords(new ArrayList<>());
                        emptyView.setVisibility(View.VISIBLE);
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "SearchRunnable: 搜索出错: " + e.getMessage(), e);
                
                // 在主线程显示错误
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    ToastManager.showShort(getContext(), "搜索出错: " + e.getMessage());
                });
            }
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 移除搜索任务
        if (mainHandler != null && searchRunnable != null) {
            mainHandler.removeCallbacks(searchRunnable);
        }
        Log.d(TAG, "onDestroy: 词典Fragment被销毁");
    }
} 